import { useEffect, useState } from 'react'
import { HashRouter as Router, useLocation, useHistory } from 'react-router-dom'
import { Provider, useDispatch, useSelector } from 'react-redux'
import { message } from 'antd';

import store from './store'

import AppLayout from './components/layout/AppLayout'
import AppHeader from './components/layout/AppHeader'
import AppNav from './components/layout/AppNav'
import AppContent from './components/layout/AppContent'

import { queryCurUserAction } from './store/actions/userActions'
import { queryAppDefinitionAction, setCurAppAction } from "./store/actions/appDefAction"


const AppComp = () => {

  const [loaded, setLoaded] = useState(false)
  const location = useLocation()
  const history = useHistory()
  const dispatch = useDispatch()
  const appDefinitionList = useSelector(state => state.appDef.list)

  useEffect(() => {
    if (appDefinitionList.length) {
      const appKey = localStorage.getItem('appKey')
      if (appKey) {
        dispatch(setCurAppAction(appKey))
      }
    }
  }, [appDefinitionList])

  const hideLoading = () => {
    const loadingEl = document.querySelector('#J_loading')
    loadingEl && loadingEl.remove()
    setLoaded(true)
  }

  const loadAppDefinitions = async () => {
    try {
      await dispatch(queryAppDefinitionAction())
      hideLoading()
    } catch (error) {
      hideLoading()
    }
  }

  const initApp = async () => {
    if (location.pathname !== '/login') {
      try {
        await dispatch(queryCurUserAction())
        loadAppDefinitions()
      } catch (error) {
        hideLoading()
        history.push('/login')
      }
    } else {
      hideLoading()
    }
  }

  useEffect(initApp, [])

  return loaded && <AppLayout
    header={<AppHeader />}
    nav={<AppNav />}
    content={<AppContent />}
  ></AppLayout>
}

const App = () => {
  return <Provider store={store}>
    <Router>
      <AppComp />
    </Router>
  </Provider>
}

export default App
